<template>
  <div class="package-detail">
    <el-card v-if="packageDetail" class="detail-card">
      <h2 class="title">{{ packageDetail.packageName }}</h2>

      <div class="info-section">
        <div class="actions">
        <el-button type="primary" @click="handleBooking">立即预约</el-button>
        <el-button @click="goBack">返回列表</el-button>
      </div>
        <div class="price-section">
          <span class="label">价格：</span>
          <span class="price">￥{{ packageDetail.price?.toFixed(2) }}</span>
        </div>
        <div class="institution-section">

          <el-button
              type="primary"
              @click="viewDetail(packageDetail.institutionId)"
              class="detail-btn">
              <span class="label">体检机构：</span>
          <span>{{ packageDetail.institutionName }}</span>
            </el-button>
        </div>
        <div class="description-section">
          <div class="label">套餐描述：</div>
          <p class="description">{{ packageDetail.description }}</p>
        </div>
      </div>

      <!-- 添加评论区 -->
      <div class="evaluations-section">
        <h3 class="evaluation-title">用户评价</h3>
        <div v-if="packageDetail.evaluations && packageDetail.evaluations.length > 0">
          <div v-for="(evaluation, index) in packageDetail.evaluations"
               :key="index"
               class="evaluation-item">
            <div class="evaluation-header">
              <span class="user-name">{{ evaluation.name }}</span>
              <el-rate
                v-model="evaluation.score"
                disabled
                show-score
                text-color="#ff9900"
              />
            </div>
            <p class="comment-content">{{ evaluation.comment }}</p>
          </div>
        </div>
        <div v-else class="no-evaluations">
          暂无评价
        </div>
      </div>


    </el-card>
    <el-skeleton v-else :rows="3" animated />
    <el-alert v-if="error" :title="error" type="error" show-icon :closable="false" class="error-alert" />
    <el-dialog
      v-model="bookingDialogVisible"
      title="预约体检"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="booking-form">
        <div class="date-picker">
          <span class="label">请选择预约时间：</span>
          <el-date-picker
            v-model="appointmentTime"
            type="datetime"
            placeholder="选择日期和时间"
            :disabled-date="disabledDate"
            :disabled-hours="disabledHours"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="bookingDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBooking" :loading="bookingLoading">
            确认预约
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { queryById } from '@/api/medicalPackages';
import { ElMessageBox ,ElMessage} from 'element-plus';
import { booking } from '@/api/appointments';
import { useUserStore } from '@/stores/user';

// 定义套餐详情的接口类型
interface PackageDetail {
  packageId: number;
  packageName: string;
  description: string;
  price: number;
  institutionName: string;
  institutionId: number;
  evaluations?: Array<{
    score: number;
    comment: string;
    userId: number;
    name: string;
  }>;
}

// 获取路由和路由器实例
const route = useRoute();
const router = useRouter();

// 存储套餐详情数据，初始值为null
const packageDetail = ref<PackageDetail | null>(null);
// 存储错误信息
const error = ref('');
// 控制预约弹窗的显示与隐藏
const bookingDialogVisible = ref(false);
// 存储选择的预约时间
const appointmentTime = ref<Date | null>(null);
// 控制确认预约按钮的加载状态
const bookingLoading = ref(false);
// 获取用户相关的存储数据
const userStore = useUserStore();
// 获取当前日期时间
const currentDate = new Date();


// 查看详情
const viewDetail = (institutionId: number) => {
  router.push({
    name: 'medicalInstitutions-detail',
    params: { id: institutionId }
  })
}

// 定义获取套餐详情的异步函数
const fetchPackageDetail = async () => {
  const id = Number(route.params.id);
  if (!id) {
    // 如果套餐ID无效，设置错误信息并返回
    error.value = '无效的套餐ID';
    return;
  }
  try {
    const res = await queryById(id);
    if (res.code === 1 && res.msg === 'Success') {
      // 如果获取成功，更新套餐详情数据
      packageDetail.value = res.data;
    } else {
      // 如果获取失败，设置错误信息
      error.value = '获取套餐详情失败';
    }
  } catch (err) {
    // 捕获异常，记录错误日志并设置错误信息
    console.error('获取套餐详情错误:', err);
    error.value = '获取套餐详情失败，请稍后重试';
  }
};

// 定义禁用过去日期的函数
const disabledDate = (time: Date) => {
  return time.getTime() < currentDate.getTime() - 8.64e7; // 不包括今天之前的日期
};

// 定义限制可选时间为工作时间 9:00-17:00 的函数
const disabledHours = () => {
  const hours = [];
  for (let i = 0; i < 24; i++) {
    if (i < 9 || i > 17) {
      hours.push(i);
    }
  }
  return hours;
};

// 定义预约处理函数
const handleBooking = () => {
  if (!userStore.isLoggedIn) {
    // 如果用户未登录，提示登录并跳转到登录页面
    ElMessageBox.alert('请先登录后再进行预约');
    router.push('/login');
    return;
  }
  // 显示预约弹窗
  bookingDialogVisible.value = true;
};

// 定义确认预约的异步函数
const confirmBooking = async () => {
  if (!appointmentTime.value) {
    // 如果未选择预约时间，提示选择时间
    ElMessageBox.alert('请选择预约时间');
    return;
  }
  // 设置确认预约按钮为加载状态
  bookingLoading.value = true;
  try {
    const res = await booking({
      packageId: packageDetail.value?.packageId as number,
      appointmentTime: appointmentTime.value
    });
    if (res.code === 1 && res.msg === 'Success') {
      // 如果预约成功，提示成功并隐藏弹窗
      ElMessage('预约成功');
      bookingDialogVisible.value = false;
      //router.push('/my-appointments') // 假设有一个我的预约列表页面
    } else {
      // 如果预约失败，提示失败信息
      ElMessage(res.msg || '预约失败');
    }
  } catch (err) {
    // 捕获异常，记录错误日志并提示失败信息
    console.error('预约错误:', err);
  } finally {
    // 无论成功与否，都将确认预约按钮的加载状态设为false
    bookingLoading.value = false;
  }
};

// 定义返回上一页的函数
const goBack = () => {
  router.back();
};

// 在组件挂载完成后调用获取套餐详情的函数
onMounted(fetchPackageDetail);
</script>

<style scoped lang="scss">
.package-detail {
  max-width: 800px;
  margin: 2rem auto;
  padding: 0 1rem;
 .detail-card {
    .title {
      text-align: center;
      color: #303133;
      margin-bottom: 2rem;
    }
   .info-section {
      margin-bottom: 2rem;
     .price-section,
     .institution-section {
        margin-bottom: 1rem;
       .label {
          color: #606266;
          margin-right: 0.5rem;
        }
       .price {
          color: #f56c6c;
          font-size: 1.5rem;
          font-weight: bold;
        }
      }
     .description-section {
        .label {
          color: #606266;
          margin-bottom: 0.5rem;
        }
       .description {
          line-height: 1.6;
          color: #4267b1;
          white-space: pre-line;
        }
      }
    }
   .evaluations-section {
      margin-top: 2rem;
      border-top: 1px solid #ebeef5;
      padding-top: 1rem;

      .evaluation-title {
        color: #303133;
        margin-bottom: 1rem;
      }

      .evaluation-item {
        padding: 1rem;
        border-bottom: 1px solid #ebeef5;

        .evaluation-header {
          display: flex;
          align-items: center;
          margin-bottom: 0.5rem;

          .user-name {
            margin-right: 1rem;
            color: #606266;
            font-weight: bold;
          }
        }

        .comment-content {
          color: #606266;
          line-height: 1.6;
        }
      }

      .no-evaluations {
        text-align: center;
        color: #909399;
        padding: 1rem;
      }
    }
   .actions {
      display: flex;
      justify-content: center;
      gap: 1rem;
    }
  }
 .error-alert {
    margin-top: 1rem;
  }
}
.booking-form {
 .date-picker {
    margin-top: 20px;
   .label {
      display: block;
      margin-bottom: 10px;
      color: #606266;
    }
  }
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
